define(function( require ) {
    var Marionette = require('marionette');

    var tpl = require('text!components/image/1.0.0/templates/image_download.html');
    return Marionette.ItemView.extend({
        tagName: 'form',
        className: 'form-horizontal',
        template: _.template(tpl),
        ui: {
            'input': '.js-web-img-input',
            'preview': '.js-preview-download-img'
        },
        events: {
            'click .js-preview-img': 'previewImage'
        },
        previewImage: function(e) {
            var $tar = $(e.target),
                that = this;

            var src = this.ui.input.val();
            if ($.trim(src) === '') {
                this.ui.input.focus();
                return;
            }

            $tar.button('loading');
            this.model.set('src', src);
            var $container = this.ui.preview;
            var img = $('<img>').on('load', function() {
                $container.removeClass('loading');
            }).attr('src', src);
            $container.html(img).addClass('loading');
            this.model.sync({
                always: function() {
                    $tar.button('reset');
                },
                success: function() {
                    that.clearDownload();
                }
            });
        },
        clearDownload: function() {
            this.ui.preview.empty();
            this.ui.input.val('');
        }
    });
});